package com.bestcem.xm.ticket.grpc.client;

import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.messagecenter.grpc.v1.services.GetDefaultTemplateRequest;
import com.bestcem.xm.messagecenter.grpc.v1.services.GetDefaultTemplateResponse;
import com.bestcem.xm.messagecenter.grpc.v1.services.MessagecenterServiceGrpc;
import com.bestcem.xm.ticket.grpc.client.enums.messagecenter.TemplateScenarioEnum;
import com.bestcem.xm.ticket.grpc.client.enums.messagecenter.TemplateTypeEnum;
import com.bestcem.xm.ticket.service.manager.notify.dto.NotifyMessageDTO;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
import zhongyan.xm.base.v1.Base.Code;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Objects;

/**
 * 消息库模块 grpc接口
 *
 * @author XiaoYunSong <ys.xiao@idiaoyan.com>
 * @version v1.0
 * @date 2021/11/24 11:20
 */
@Slf4j
@Service
public class TicketMessageCenterGrpcService {

    @GrpcClient(GrpcClientNames.DS_QDES)
    private MessagecenterServiceGrpc.MessagecenterServiceBlockingStub messagecenterServiceBlockingStub;

    /**
     * 获取工单默认通知模板
     *
     * @param orgId    公司id
     * @param scenario 使用场景 | 默认: 邮件投放
     * @param type     模板类型 | 默认: 邮件模板
     * @return 通知模板
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/11/24 11:20
     */
    @Nullable
    public NotifyMessageDTO getDefaultTemplate(@Nonnull String orgId, @Nullable TemplateScenarioEnum scenario,
                                               @Nullable TemplateTypeEnum type) {
        if (!ObjectId.isValid(orgId)) {
            return null;
        }
        GetDefaultTemplateRequest.Builder builder = GetDefaultTemplateRequest.newBuilder();
        builder.setOrgId(orgId);
        if (Objects.nonNull(type)) {
            builder.setType(type.getInfo());
        }
        if (Objects.nonNull(scenario)) {
            builder.setScenario(scenario.getInfo());
        }
        try {
            GetDefaultTemplateResponse response = messagecenterServiceBlockingStub.getDefaultTemplate(builder.buildPartial());
            if (Objects.isNull(response) || Code.ERROR.equals(response.getStatus().getCode())) {
                log.error("[Ticket] MessageCenter getDefaultTemplate {};{};{} Error; ErrorMsg: {}", orgId, type, scenario,
                        response);
                return null;
            }
            return new NotifyMessageDTO(response.getSubject(), response.getContent());
        } catch (Exception e) {
            log.error("[Ticket] MessageCenter getDefaultTemplate {};{};{} Error;", orgId, type, scenario, e);
            return null;
        }
    }
}
